<?php
/**
 * User: 云喵
 * Agreement: 禁止使用本软件（系统）用于任何违法违规业务或项目,造成的任何法律后果允由使用者（或运营者）承担
 * Date: 2021/3/3
 * Time: 14:34
 */
namespace app\common\controller;
use think\Db;
use think\Controller;

class zfb_dmf extends Controller
{
    public function getReturn($code = 1, $data = "成功", $json = null)
    {
        return array("code" => $code, "data" => $data, "json" => $json);
    }
    
    public function cehsald($atad)//监控回调
    {
        $sz = Db::name("pay_sz")->find();
        $row = Db::name("pay_gfg")->where("pid", $atad['pid'])->where("mid",$atad['mid'])->find();
        /*** 请填写以下配置信息 ***/
        $appid = $row['zhanghao'];  //https://open.alipay.com 账户中心->密钥管理->开放平台密钥，填写对应应用的APPID
        $outTradeNo = $atad['pay_id'];     //要查询的商户订单号。注：商户订单号与支付宝交易号不能同时为空
        $tradeNo = '';     //要查询的支付宝交易号。注：商户订单号与支付宝交易号不能同时为空
        $signType = 'RSA2';       //签名算法类型，使用RSA2
        //商户私钥，填写对应签名算法类型的私钥，如何生成密钥参考：https://docs.open.alipay.com/291/105971和https://docs.open.alipay.com/200/105310
        $rsaPrivateKey=$row['ck'];
        /*** 配置结束 ***/
        //请求参数
        $requestConfigs = array(
            'out_trade_no'=>$outTradeNo,
            'trade_no'=>$tradeNo,
        );
        $commonConfigs = array(
            //公共参数
            'app_id' => $appid,
            'method' => 'alipay.trade.query',//接口名称
            'format' => 'JSON',
            'charset'=> 'utf-8',
            'sign_type'=>'RSA2',
            'timestamp'=>date('Y-m-d H:i:s'),
            'version'=>'1.0',
            'biz_content'=>json_encode($requestConfigs),
        );
        $commonConfigs["sign"] = $this->generateSign($rsaPrivateKey,$commonConfigs, $commonConfigs['sign_type']);
        $result = $this->curlPost('https://openapi.alipay.com/gateway.do?charset=utf-8',$commonConfigs);
        $json = json_decode($result,TRUE);
        if($json['alipay_trade_query_response']['code']!='10000'){
	        return $this->getReturn(-1,"交易失败", $atad); 
        }else{
	        switch($json['alipay_trade_query_response']['trade_status']){
		        case 'WAIT_BUYER_PAY':
			        return $this->getReturn(-1,"交易失败", $atad);
			        break;
		        case 'TRADE_CLOSED':
			        return $this->getReturn(-1,"交易失败", $atad);
			        break;
		        case 'TRADE_SUCCESS':
			        return $this->getReturn(1,"交易成功", $atad);
			        break;
		        case 'TRADE_FINISHED':
			        return $this->getReturn(-1,"交易失败", $atad);
			        break;
		        default:
			        return $this->getReturn(-1,"交易失败", $atad);
			        break;
	        }
        }
    }
    
    public function fukyem($data)//支付页面
    {
        $sz = Db::name("pay_sz")->find();
        $atad= Db::name("pay_gfg")->where("pid", $data['pid'])->where("mid", $data['mid'])->find();
        $user = Db::name("pay_user")->where("id", $data['pid'])->find();
        $data['timeOut'] = $user['bug_close'];//订单有效期
        
        if($data['type']=='alipay'){//支付宝
        
            if($atad['ms']==0){//H5
            
                $data['order_url'] = '<script language="javascript" type="text/javascript">window.location.href="'.$data['mid_url'].'";</script>';//H5链接
                // 模板变量赋值
                $this->assign('data',$data);
                return $this->fetch('pay/fxh5');
            
            }else{//扫码
                $data['src'] = url('pay/enQrcode').'?url='.$data['mid_url'];//二维码
                // 模板变量赋值
                $data['luji'] = '../../static/pay/pay_'.$sz['web_pay'];//模板路径
                $this->assign('data',$data);
                return $this->fetch('pay/pay_'.$sz['web_pay'].'/index');
            }
            
        }
    }
    
    public function exec($atad,$money,$type)
    {
        /*** 请填写以下配置信息 ***/
        $appid = $atad['zhanghao'];  //https://open.alipay.com 账户中心->密钥管理->开放平台密钥，填写添加了电脑网站支付的应用的APPID
        $notifyUrl = "";     //付款成功后的异步回调地址
        $outTradeNo = time();     //你自己的商品订单号，不能重复
        $payAmount = $money;          //付款金额，单位:元
        $orderName = '公益捐赠';    //订单标题
        $signType = 'RSA2';			//签名算法类型，支持RSA2和RSA，推荐使用RSA2
        $rsaPrivateKey=$atad['ck'];		//商户私钥，填写对应签名算法类型的私钥，如何生成密钥参考：https://docs.open.alipay.com/291/105971和https://docs.open.alipay.com/200/105310
        /*** 配置结束 ***/
        
        //请求参数
        $requestConfigs = array(
            'out_trade_no'=>$outTradeNo,
            'total_amount'=>$payAmount, //单位 元
            'subject'=>$orderName,  //订单标题
            'timeout_express'=>'2h'       //该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        );
        $commonConfigs = array(
            //公共参数
            'app_id' => $appid,
            'method' => 'alipay.trade.precreate',//接口名称
            'format' => 'JSON',
            'charset'=> 'utf-8',
            'sign_type'=>'RSA2',
            'timestamp'=>date('Y-m-d H:i:s'),
            'version'=>'1.0',
            'notify_url' => $notifyUrl,
            'biz_content'=>json_encode($requestConfigs),
        );
        $commonConfigs["sign"] = $this->generateSign($rsaPrivateKey,$commonConfigs, $commonConfigs['sign_type']);
        $result = $this->curlPost('https://openapi.alipay.com/gateway.do?charset=utf-8',$commonConfigs);
        $json = json_decode($result,TRUE);
        $json = $json['alipay_trade_precreate_response'];
        if($json['code'] && $json['code']=='10000'){
            $atad['pay_id'] = $json['out_trade_no'];//通道订单号
            $atad['mid_url'] = $json['qr_code'];//通道二维码
            return $this->getReturn(1, $atad, $ret);
        }else if($json['sub_msg']=='缺少签名参数'){
            return $this->getReturn(-1, $atad['typec_name'].'商户私钥错误');
        }else{
            return $this->getReturn(-1, $atad['typec_name'].$json['sub_msg']);
        }
    }
    
    public function generateSign($priKey,$params, $signType = "RSA") {
        return $this->sign($priKey,$this->getSignContent($params), $signType);
    }
    protected function sign($priKey,$data, $signType = "RSA") {
        error_reporting(0);
        $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
            wordwrap($priKey, 64, "\n", true) .
            "\n-----END RSA PRIVATE KEY-----";
        ($res) or die($this->getReturn(-1, $atad['typec_name'].'您使用的私钥格式错误，请检查RSA私钥配置'));
        if ("RSA2" == $signType) {
            openssl_sign($data, $sign, $res, version_compare(PHP_VERSION,'5.4.0', '<') ? SHA256 : OPENSSL_ALGO_SHA256); //OPENSSL_ALGO_SHA256是php5.4.8以上版本才支持
        } else {
            openssl_sign($data, $sign, $res);
        }
        $sign = base64_encode($sign);
        return $sign;
    }
    protected function checkEmpty($value) {
        if (!isset($value))
            return true;
        if ($value === null)
            return true;
        if (trim($value) === "")
            return true;
        return false;
    }
    public function getSignContent($params) {
        ksort($params);
        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
                // 转换成目标字符集
                $v = $this->characet($v, 'utf-8');
                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i++;
            }
        }
        unset ($k, $v);
        return $stringToBeSigned;
    }
    function characet($data, $targetCharset) {
        if (!empty($data)) {
            $fileType = 'utf-8';
            if (strcasecmp($fileType, $targetCharset) != 0) {
                $data = mb_convert_encoding($data, $targetCharset, $fileType);
                //$data = iconv($fileType, $targetCharset.'//IGNORE', $data);
            }
        }
        return $data;
    }
    public function curlPost($url = '', $postData = '', $options = array())
    {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    
}